package com.java.base.exercise.designmode.composite;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author RenPu
 * @Date 2021/6/25 13:05
 * @Version 1.0
 * @Description: 设计模式---组合模式：用于解决数状结构的数据处理
 **/
abstract class Node {

    abstract public void printResult();
}

class LeftNode extends Node {

    String content;

    public LeftNode() {
    }

    public LeftNode(String content) {
        this.content = content;
    }

    @Override
    public void printResult() {
        System.out.println("leftNode:" + content);

    }
}

class BranchNode extends Node {

    String name;

    List<Node> nodeList = new ArrayList<>();

    public BranchNode() {
    }

    public BranchNode(String name) {
        this.name = name;
    }

    @Override
    public void printResult() {
        System.out.println("BranchNode:" + name);
    }

    public void add(Node n) {
        nodeList.add(n);
    }
}

class Main {
    public static void main(String[] args) {

        BranchNode root = new BranchNode("root");
        BranchNode chapter1 = new BranchNode("chapter1");
        BranchNode chapter2 = new BranchNode("chapter2");
        LeftNode cell1 = new LeftNode("cell1");
        LeftNode cell2 = new LeftNode("cell2");
        BranchNode selection2 = new BranchNode("selection2");
        Node c211 = new LeftNode("c211");
        Node c212 = new LeftNode("c212");

        root.add(chapter1);
        root.add(chapter2);
        chapter1.add(cell1);
        chapter1.add(cell2);
        chapter2.add(selection2);
        selection2.add(c211);
        selection2.add(c212);

        tree(root, 0);

    }

    private static void tree(Node root, int depth) {

        for (int i = 0; i < depth; i++) System.out.print("--");

        root.printResult();
        if (root instanceof BranchNode) {
            for (Node n : ((BranchNode) root).nodeList) {
                tree(n, depth + 1);
            }

        }


    }
}
